import React, { useEffect, useState } from 'react';
import {  Card, Grid, Toast, ImageViewer, Popup, List,Dialog } from 'antd-mobile';
import { 
    CalendarOutline,
    UnorderedListOutline,
    TeamOutline,
    ClockCircleOutline,
    EnvironmentOutline,
    CouponOutline,
    MessageOutline,
    UserContactOutline,
    SetOutline,
    LockOutline,
    DeleteOutline,
} from 'antd-mobile-icons';
import { history } from 'umi';
import { userAPI } from '@/services/api';
import type { UserInfo } from '@/services/api';
import { useUserStore } from '@/stores/userStore';
import styles from './index.less';
import { IMAGES } from '@/config/images';

const User: React.FC = () => {
    const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
    const [showImageViewer, setShowImageViewer] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const logout = useUserStore(state => state.logout);

    useEffect(() => {
        fetchUserInfo();
    }, []);

    const fetchUserInfo = async () => {
        try {
            const res = await userAPI.getUserInfo();
            if (res.code === 200) {
                setUserInfo(res.data);
            }
        } catch (error) {
            console.error('Failed to fetch user info:', error);
        }
    };

    const menuItems = [
        { icon: <CalendarOutline />, text: '课卡信息', path: '/card-info' },
        { icon: <UnorderedListOutline />, text: '预约记录', path: '/appointments' },
        { icon: <TeamOutline />, text: '排队记录', path: '/queue-records' },
        { icon: <ClockCircleOutline />, text: '上课记录', path: '/class-records' },
        { icon: <EnvironmentOutline />, text: '我的云课堂', path: '/online-class' },
        { icon: <UserContactOutline />, text: '我是家长', path: '/parent' },
        { icon: <MessageOutline />, text: '消息订阅', path: '/messages' },
        { icon: <CouponOutline />, text: '我的优惠券', path: '/coupons' },
    ];

    const handleLogout = () => {
        Dialog.confirm({
            title: '退出登录',
            content: '确定要退出登录吗？',
            onConfirm: () => {
                logout();
                localStorage.removeItem('token');
                history.replace('/login');
            },
        });
    };

    const handleChangePassword = () => {
        Toast.show({
            content: '修改密码功能开发中...',
            position: 'bottom',
        });
    };

    return (
        <div className={styles.userContainer}>
            {/* 用户信息卡片 */}
            <div className={styles.userCard}>
                <div className={styles.cardHeader}>
                    <SetOutline 
                        className={styles.settingIcon} 
                        onClick={() => setShowSettings(true)}
                    />
                </div>
                
                <div className={styles.userInfo}>
                    <img 
                        src={userInfo?.avatar_url || IMAGES.DEFAULT_AVATAR}
                        className={styles.avatar}
                        onClick={() => setShowImageViewer(true)}
                        alt="头像"
                    />
                    <div className={styles.userDetail}>
                        <div className={styles.name}>
                            {userInfo?.real_name || userInfo?.username || '未设置昵称'}
                        </div>
                        <div className={styles.phone}>
                            {userInfo?.phone || '未绑定手机号'}
                        </div>
                        {userInfo?.email && (
                            <div className={styles.email}>{userInfo.email}</div>
                        )}
                    </div>
                </div>
                
                <div className={styles.userMeta}>
                    <div className={styles.metaItem}>
                        <span className={styles.label}>角色：</span>
                        <span className={styles.value}>
                            {userInfo?.role_name === 'student' ? '学员' : 
                             userInfo?.role_name === 'teacher' ? '教师' : '管理员'}
                        </span>
                    </div>
                    <div className={styles.metaItem}>
                        <span className={styles.label}>状态：</span>
                        <span className={styles.value}>
                            {userInfo?.status === 'active' ? '正常' : '已禁用'}
                        </span>
                    </div>
                </div>
                
                {/* 统计信息 */}
                <div className={styles.statsBar}>
                    <div className={styles.statsItem}>
                        <div className={styles.statsValue}>2次</div>
                        <div className={styles.statsLabel}>上课次数</div>
                    </div>
                    <div className={styles.divider} />
                    <div className={styles.statsItem}>
                        <div className={styles.statsValue}>101名</div>
                        <div className={styles.statsLabel}>排名(200)</div>
                    </div>
                </div>
            </div>

            {/* 我的资产卡片 */}
            <Card className={styles.assetCard}>
                <div className={styles.assetTitle}>我的资产</div>
                <div className={styles.assetContent}>
                    <span className={styles.assetLabel}>钱包余额</span>
                    <span className={styles.assetValue}>¥ 0.00</span>
                    <span className={styles.viewDetail}>查看明细 &gt;</span>
                </div>
            </Card>

            {/* 功能菜单 */}
            <div className={styles.menuGrid}>
                <Grid columns={4} gap={8}>
                    {menuItems.map((item, index) => (
                        <Grid.Item key={index}>
                            <div className={styles.menuItem}>
                                <div className={styles.menuIcon}>{item.icon}</div>
                                <div className={styles.menuText}>{item.text}</div>
                            </div>
                        </Grid.Item>
                    ))}
                </Grid>
            </div>

            {/* 设置抽屉 */}
            <Popup
                visible={showSettings}
                onMaskClick={() => setShowSettings(false)}
                position='right'
                bodyStyle={{ 
                    width: '50vw',
                    height: '100vh',
                    background: 'linear-gradient(to bottom, #f8f9fa, #fff)'
                }}
            >
                <div className={styles.settingsPopup}>
                    <div className={styles.settingsHeader}>
                        <span>设置</span>
                        <SetOutline className={styles.settingIcon} onClick={() => setShowSettings(false)} />
                    </div>
                    <List className={styles.settingsList}>
                        <List.Item
                            prefix={<LockOutline className={styles.settingIcon} />}
                            onClick={handleChangePassword}
                        >
                            修改密码
                        </List.Item>
                        <List.Item
                            prefix={<DeleteOutline className={styles.settingIcon} />}
                            onClick={handleLogout}
                            className={styles.logoutItem}
                        >
                            退出登录
                        </List.Item>
                    </List>
                </div>
            </Popup>

            {/* 图片预览器 */}
            <ImageViewer
                image={userInfo?.avatar_url || IMAGES.DEFAULT_AVATAR}
                visible={showImageViewer}
                onClose={() => setShowImageViewer(false)}
            />
        </div>
    );
};

export default User; 